//index.js
//获取应用实例
const app = getApp()
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
Page({
  data: {
    weatherweek:[],//七日精确天气
    weatherRoughweek:[],//七日天气简略版
    nowWeatherImg:"/img/qing.png",//实时天气图片
    weatherImgList:[],//24小时天气的图片list
    province:"",//省份
    city:"",//城市
    district:"",//地区
    latitude:"",//经度
    longitude:"",//纬度
    huanhang:"\n",//换行
    sevenWeatherImgList:[],//7天天气的图片list
    setData:[],
    weatherTime:[]
  },
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中'
    })   
    setTimeout(function () {
      wx.hideLoading()
    }, 1000)
      qqmapsdk = new QQMapWX({
      key:'GTDBZ-FUEOK-FXEJU-AGZST-UO6P5-SIBDJ' //这里自己的key秘钥进行填充
    });
    
    this.getUserInfo();
    if(options){
      this.setData({
        latitude:options.latitude,
        longitude:options.longitude
      })
    }
    console.log('lat1111',this.data.latitude,'lng22',this.data.longitude)
  },
  add0:function (m){
    return m < 10 ? '0' + m : m
  },
  formatDate:function(value){
    let time = new Date(value);
                let m = time.getMonth()+1;
                let d = time.getDate();             
                return this.add0(m) + '/' + this.add0(d);
  },
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    setTimeout(function () {
    // complete
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
    }, 1500);
    },
  getUserInfo:function(){
    let vm = this;
    wx.getSetting({
      success: (res) => {
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
               
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                     
                    }
                  }
                })
              }
            }
            
          }
         )
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          vm.getLocation();
        }else {
          //调用wx.getLocation的API
          vm.getLocation();
        }
        setTimeout(function () {
          wx.hideLoading()
        }, 500)
      }
    })
  },
  // 微信获得经纬度
  getLocation: function () {
    let vm = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        console.log('lat3333',vm.data.latitude,'lng4444',vm.data.longitude)
        if(vm.data.latitude &&vm.data.longitude){
          vm.getLocal(vm.data.latitude,vm.data.longitude)
        }else{
          vm.getLocal(latitude, longitude)
        }
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
      }
    })
  },
  // 获取当前地理位置
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        console.log('diliweizhi11111',res)
        
        let province = res.result.ad_info.province
        let city = res.result.ad_info.city
        let district = res.result.ad_info.district
        app.setLocal(city)
        district = district.substring(0, district.length - 1);
        
        vm.setData({
          province: province,
          city: city,
          latitude: latitude,
          longitude: longitude,
          district: district
        })

        vm.weatherweekday(district);
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function () {
        // console.log(res);
      }
    });
  },


  // 天气api天气获取, 请更换为自己的appid和appsecret
  weatherweekday: function (district) {
    var _this = this;
    wx.request({
      url: 'https://www.tianqiapi.com/api/?version=v9&appid=75683827&appsecret=0Jh3TCAh&vue=1',
      // url: 'https://www.tianqiapi.com/free/week?appid=75683827&appsecret=0Jh3TCAh',
      data: {
        'city': district,
        // 'cityid': "101120302"
      },
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var weatherImg = [];
        res.data.data[0].hours.forEach(element => {
          weatherImg.push("/img/" + element.wea_img + ".png",)
        });
        var sevenweatherImg = []
        res.data.data.forEach(element => {
          sevenweatherImg.push("/img/" + element.wea_img + ".png",)
        })
        wx.showToast({
          title: '成功',
           icon: 'success',
          duration: 1000
        })
        var weatherTime = []
        res.data.data[0].hours.forEach(element => {
          weatherTime.push(element.hours.substr(0, 2)+':00')
        })
        var sevenDate = []
        res.data.data.forEach(element => {
          sevenDate.push(_this.formatDate(element.date))
        })
        _this.setData({
          weatherweek: res.data,
          nowWeatherImg: "/img/" + res.data.data[0].wea_img + ".png",
          weatherImgList: weatherImg,
          sevenWeatherImgList:sevenweatherImg,
          sevenDate:sevenDate,
          weatherTime:weatherTime
        });
        console.log('天气api接口返回数据',_this.data.weatherweek)
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
        wx.showToast({
          title: '失败',
           icon: 'none',
          duration: 1000
        })
      
      }
    });
  },
    onTapAddress() {
      wx.redirectTo({
        url: '../search/search'
      })
  
      // this.getLocal(this.data.latitude,this.data.longitude)
    }
})
